import { PermissionModel } from "./.server/models/permission";
import { TreeNode } from "./types";

export function toTreeNode(permissions: PermissionModel[]): TreeNode[] {
  if (!permissions) return [];
  return permissions.map(permission => ({
    ...permission,
    id: (permission.id ?? "").toString(),
    name: permission.name ?? "",
    children: permission.children ? toTreeNode(permission.children) : []
  }));
}
export function findPermission(permissions: PermissionModel[], permissionId: number): PermissionModel | null {
  for (const permission of permissions) {
    if (permission.id === permissionId) {
      return permission;
    }
    if (permission.children) {
      const foundPermission = findPermission(permission.children, permissionId);
      if (foundPermission) {
        return foundPermission;
      }
    }
  }
  return null;
}
export function filterPermissionByKeyword(permissions: PermissionModel[], keyword: string): PermissionModel[] | [] {
  // 递归过滤
  const filteredPermissions: PermissionModel[] = [];
  for (const permission of permissions) {
    if (permission.name?.includes(keyword)
      || permission.zh_name?.includes(keyword)
      || permission.path?.includes(keyword)
    ) {
      filteredPermissions.push(permission);
    } else if (permission.children) {
      const childFilteredPermissions = filterPermissionByKeyword(permission.children, keyword);
      if (childFilteredPermissions) {
        filteredPermissions.push(...childFilteredPermissions);
      }
    }
  }
  return filteredPermissions;
}

export function uniqueID(length: number = 10) {
  return `_${Math.random()
    .toString(36)
    .substring(2, length)}`;
}

export function convertNullToUndefined<S extends object, T extends object>(obj: S): T {
  return Object.fromEntries(
    Object.entries(obj).map(([key, value]) => [key, value === null ? undefined : value])
  ) as T;
}
